import { createStore } from 'vuex'
import router from '@/router'
import {getHomeNotice, getUser, loginout,sendCode} from '@/axios'
import { message, Modal } from 'ant-design-vue'
import VuexPersist from 'vuex-persist'
import TCaptcha from '@/plugin/TCaptcha'
import {validateCode, validatePassword} from '@/plugin/validate'
const tcaptcha = new TCaptcha()

const vuexPersist = new VuexPersist({
  key: 'userInfo',
  storage: window.localStorage,
  modules: ['userInfo']
})

export default createStore({
  state: {
    isLogin: false,
    userInfo: {},
    passwordSet: 0,
    httpRequestList: [],
    queryForm: {
      type: 1,
      url: '',
      ua: 16
    },
    rules: {
      password: [{required: true, validator: validatePassword}],
      code: [{required: true, validator: validateCode}]
    },
    historyRecord: localStorage.historyRecord ? JSON.parse(localStorage.historyRecord) : [],
    provinceList: ['安徽','北京','重庆','福建','甘肃','广西','广东','贵州','海南','河北','河南','黑龙江','湖南','湖北','吉林','江西','江苏','辽宁','内蒙古','宁夏','青海','陕西','山西','山东','上海','四川','天津','西藏','新疆','云南','浙江'],
    urlReg: /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[\w\#](\?)?)*)*$/,
    phoneReg: /^(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
    showCountDown: false,
    countTimer: null,
    countDownNum: 60,
    noticeList: {},
    frontRoute: ['/','/help','/about','/product']
  },
  mutations: {
    changeState (state,data){
      state[data[0]] = data[1]
    },
    addHttpRequestList(state, payload) {
      if (payload == 0) {
        state.httpRequestList.forEach(item => item('suspend'))// 添加标识，中断请求
        state.httpRequestList = []
      } else {
        state.httpRequestList.push(payload)
      }
    },
    // checkIsBindMobile(state){
    //   if(!state.userInfo.mobile){
    //     Modal.warning({
    //       title: '安全提示',
    //       content: '检测到您当前账号暂未绑定手机，为了您的账号安全以及产品正常使用，请先绑定手机后再进行使用。',
    //       okText: '前去绑定',
    //       okType: 'primary',
    //       keyboard: false,
    //       centered: true,
    //       class: 'safety-tips',
    //       onOk() {
    //         router.push( '/account')
    //       }
    //     })
    //   }
    // },
    getYzm (state,mobile){
      if (!mobile && !state.phoneReg.test(mobile)) return false
      tcaptcha.getTCaptcha(async data => {
        if(data.CaptchaCode === 1){
          const res = await sendCode({mobile})
          if (res.code === 1) {
            message.success(res.msg)
            state.showCountDown = true
            state.countTimer = setInterval(()=>{
              if(state.countDownNum >= 1){
                state.countDownNum --
              }else{
                clearInterval(state.countTimer)
                state.showCountDown = false
                state.countDownNum = 60
              }
            },1000)
          } else {
            message.error(res.msg)
          }
        }else{
          message.error('验证失败')
        }
      })
    },
    resetCountDown(state){
      clearInterval(state.countTimer)
      state.showCountDown = false
      state.countDownNum = 60
    },
    logout (state) {
      loginout().then(res => {
        localStorage.removeItem('userToken')
        state.isLogin = false
        state.userInfo = {}
        if(res.code === 0){
          window.location.pathname !== '/' ? router.replace('/') : ''
          message.success(res.msg)
        }else{
          message.error(res.msg)
        }
      })
    },
    async getNoice(state){
      const res = await getHomeNotice()
      res.code === 0 ? state.noticeList = res.data : message.error(res.msg)
    }
  },
  actions: {
    // 移除请求
    async removeHttpRequestList(ctx) {
      ctx.commit('addHttpRequestList', 0)
    },
    queryLink(ctx){
      if(localStorage.historyRecord && JSON.parse(localStorage.historyRecord).length > 0){
        const oldRecord = JSON.parse(localStorage.historyRecord)
        const index = oldRecord.indexOf(this.state.queryForm.url)
        if(index === -1){
          oldRecord.unshift(this.state.queryForm.url) > 10 ? oldRecord.pop() : ''
          ctx.commit('changeState',['historyRecord',oldRecord])
          localStorage.setItem('historyRecord',JSON.stringify(oldRecord))
        }
      }else{
        const historyUlrArr = [this.state.queryForm.url]
        ctx.commit('changeState',['historyRecord',[this.state.queryForm.url]])
        localStorage.setItem('historyRecord',JSON.stringify(historyUlrArr))
      }
      // router.replace(`/check?url=${this.state.queryForm.url}`)
      location.href = `${location.origin}/check?url=${this.state.queryForm.url}`
    },
    removeHistory(ctx,type){
      if (type === 'all' || this.state.historyRecord.length === 1){
        ctx.commit('changeState',['historyRecord',[]])
        localStorage.removeItem('historyRecord')
        message.success('清除成功')
      }else{
        const index = this.state.historyRecord.indexOf(type)
        if(index !== -1){
          const newRecord = JSON.parse(JSON.stringify(this.state.historyRecord))
          newRecord.splice(index, 1)
          localStorage.setItem('historyRecord',JSON.stringify(newRecord))
          ctx.commit('changeState',['historyRecord',newRecord])
          message.success('清除成功')
        }
      }
    },
    getUserInfo (ctx){
      getUser().then(async res=>{
        if(res.code === 0){
          ctx.commit('changeState', ['userInfo',res.data.data])
          ctx.commit('changeState', ['isLogin',true])
          ctx.commit('changeState', ['passwordSet',res.data.pass_set])
          ctx.commit('getNoice')
          // window.location.pathname !== '/account' ? ctx.commit('checkIsBindMobile') : ''
        }else{
          localStorage.removeItem('userToken')
          ctx.commit('changeState', ['userInfo', {}])
          ctx.commit('changeState', ['isLogin',false])
          window.location.pathname === '/account' ? router.replace('/') : ''
        }
      })
    }
  },
  modules: {},
  plugins: [vuexPersist.plugin]
})
